import {Tag} from "antd";
import LogFactory from "@/log/LogFactory.ts";
import RequestHandler from "@/http/RequestHandler.ts";
import MysqlReplica from "@/component/navigate/MysqlReplica";
import {useEffect, useRef, useState} from "react";

const log = LogFactory.getLogger("SqlStatusComponent");

const SqlStatusComponent = () => {
    // log.debug("SqlStatusComponent ===============> render");
    const [sqlRunning, setSqlRunning] = useState<boolean>(false);
    const [ioRunning, setIoRunning] = useState<boolean>(false);
    const [serverStatus, setServerStatus] = useState<boolean>(false);

    const isSend = useRef<boolean>(true);
    const reconnectionTime = useRef<number>(import.meta.env.VITE_SQL_STATUS_RECONNECTION_TIME);

    useEffect(() => {
        setTimeout(checkSqlStatus,50);
        const id = setInterval(checkSqlStatus, import.meta.env.VITE_SQL_STATUS_POLL_TIME);
        return () => {
            log.debug("组件卸载清除定时器: ", id);
            clearInterval(id)
        };
    }, []);
    const checkSqlStatus = async () => {
        if (document.visibilityState === "hidden"){
            log.debug("当前页面不可见,取消SQL状态检查");
            return;
        }
        if (!isSend.current){
            // log.debug("服务器无法连接,本次请求取消");
            setTimeout(() => {
                log.debug("服务器无法连接重试时间到,重新发送请求");
                isSend.current = true;
            }, reconnectionTime.current);
            return;
        }
        try {
            const res = await RequestHandler.get<MysqlReplica>("/main/mysql");
            // log.debug("获取SQL状态成功: ", res)
            setServerStatus(true);
            if (res.success){
                setSqlRunning(res.data.replicaSQLRunning === "Yes");
                setIoRunning(res.data.replicaIORunning === "Yes");
            }
        }catch (e){
            log.error("获取SQL状态时候出现错误: ",e);
            isSend.current = false;
            setServerStatus(false);
            setSqlRunning(false);
            setIoRunning(false);
        }
    }


    return (
        <>
            <Tag color={sqlRunning ? "#0d800d" : "#88291b"}>SQL_OK</Tag>
            <Tag color={ioRunning ? "#0d800d" : "#88291b"}>IO_OK</Tag>
            <Tag color={serverStatus ? "#0d800d" : "#88291b"}>SERVER_OK</Tag>
        </>
    );
};

export default SqlStatusComponent;